package cn.fzkj.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.cglib.beans.BeanMap;

import java.util.*;

/**
 * @DESCRIPTION: TODO 将map集合转换为实体类的工具类
 * @AUTHOR: AnotherOne
 * @DATE: 2021/7/31 14:51
 */
public class BeanMapUtils {
    /**
     * 将对象属性转化为map结合
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key+"", beanMap.get(key));
            }
        }
        return map;
    }

    /**
     * 将map集合中的数据转化为指定对象的同名属性中
     */
    public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) throws Exception {
        T bean = clazz.newInstance();
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    /**
     * 将list的map集合转换为对应bean的集合
     * @param maps
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<T> mapListToBean(List<Map<String, Object>> maps, Class<T> clazz) throws Exception {
        List<T> list = new ArrayList<>();
        T bean;
        for (Map<String, Object> map : maps) {
            bean = JSON.parseObject(JSON.toJSONString(map), clazz);
            list.add(bean);
        }
        return list;
    }

}
